<?php


namespace App\Models\CacheModel;

use App\Models\Api\BaseCache;
use Exception;
use think\Log;
use AstroTool\Cache\CacheManage;

class MentalOptionModel extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.mt_options';
    protected $cacheModel = 'mental_test.option';

    private $LOG_PRE = '心理测试-选项-Model：';

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $where = ['id' => ['in', $ids]];
            } else
            {
                $where = ['qid' => $type[0]];
            }

            $data = $this->where($where)
                ->order('id asc')
                ->column('type,pid,oid,title,label,content,option_type,picture,score,media_type,media_content_addr', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 获取选项列表
     * @param int $qid 问题id
     * @return array
     * @throws \Exception
     */
    public function getOptionList(int $qid): array
    {
        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $qid)
            ->setPage(-1)
            ->setListKeyType(0)
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'asc') use ($qid)
            {
                try
                {
                    if ($isCache)
                    {
                        return $this->getInfoByIdsInData($ids, [$qid], $sortType);
                    }
                }
                catch (Exception $e)
                {
                    Log::write($this->LOG_PRE . '查询选项表异常：' . $e->getMessage(), 'error', true);
                    return [];
                }
//
            }, 'id', ['id', 'oid', 'type', 'pid', 'title', 'label', 'content', 'option_type', 'picture', 'score', 'media_type', 'media_content_addr', 'picture', 'otype_private'], 0);

        //处理数据
        $list = [];
        foreach ($data['data'] as $k => $v)
        {
            //类型转换
            $v['option_type'] = (int)$v['option_type'];
            $v['type'] = (int)$v['type'];
            $v['score'] = (int)$v['score'];
            $v['pid'] = (int)$v['pid'];
            $v['media_type'] = (int)$v['media_type'];
            $v['id'] = (int)$v['id'];
            $data['data'][$k] = $v;

            if ($v['type'] === 1)
            {
                $list[] = $v;
            }
        }
        foreach ($list as $qK => $qV)
        {
            foreach ($data['data'] as $k => $v)
            {
                $v['label'] = trim($v['label']);
                if ((int)$v['pid'] > 0 && (int)$v['pid'] === (int)$qV['id'])
                {
                    $list[$qK]['options'][] = $v;
                }
            }
        }

        return $list;

    }

}
